import { defineStore } from 'pinia'

interface AppState {
  loading: boolean
  theme: 'light' | 'dark'
  sidebarCollapsed: boolean
  breadcrumbs: BreadcrumbItem[]
  pageTitle: string
  language: string
}

interface BreadcrumbItem {
  title: string
  path?: string
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    loading: false,
    theme: (localStorage.getItem('theme') as 'light' | 'dark') || 'light',
    sidebarCollapsed: localStorage.getItem('sidebarCollapsed') === 'true',
    breadcrumbs: [],
    pageTitle: '',
    language: localStorage.getItem('language') || 'zh-CN'
  }),

  getters: {
    isLoading: (state) => state.loading,
    getTheme: (state) => state.theme,
    isSidebarCollapsed: (state) => state.sidebarCollapsed,
    getBreadcrumbs: (state) => state.breadcrumbs,
    getPageTitle: (state) => state.pageTitle,
    getLanguage: (state) => state.language
  },

  actions: {
    // 设置加载状态
    setLoading(loading: boolean) {
      this.loading = loading
    },

    // 设置主题
    setTheme(theme: 'light' | 'dark') {
      this.theme = theme
      localStorage.setItem('theme', theme)
    },

    // 切换主题
    toggleTheme() {
      this.setTheme(this.theme === 'light' ? 'dark' : 'light')
    },

    // 设置侧边栏折叠状态
    setSidebarCollapsed(collapsed: boolean) {
      this.sidebarCollapsed = collapsed
      localStorage.setItem('sidebarCollapsed', collapsed.toString())
    },

    // 切换侧边栏折叠状态
    toggleSidebar() {
      this.setSidebarCollapsed(!this.sidebarCollapsed)
    },

    // 设置面包屑
    setBreadcrumbs(breadcrumbs: BreadcrumbItem[]) {
      this.breadcrumbs = breadcrumbs
    },

    // 设置页面标题
    setPageTitle(title: string) {
      this.pageTitle = title
      document.title = title ? `${title} - PlayEdu Admin` : 'PlayEdu Admin'
    },

    // 设置语言
    setLanguage(language: string) {
      this.language = language
      localStorage.setItem('language', language)
    },

    // 显示全局加载
    showLoading() {
      this.setLoading(true)
    },

    // 隐藏全局加载
    hideLoading() {
      this.setLoading(false)
    }
  }
})